package br.indt.framework.ui.common;

import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

public class PopupMenu extends Widget {
	
	private MenuItem[] menuItems = null;
	private int height = 0;
	private static final int MARGIN = 10;
	private Font font = null;
	private MenuItemListener listener = null;
	private int startY = 0;
	
	public PopupMenu(String name, MenuItem[] menuItems, MenuItemListener listener) {
		super(name);
		font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
		this.listener = listener;
		setItems(menuItems);
	}
	
	public void setItems(MenuItem[] menuItems) {
		this.menuItems = menuItems;
		calculateHeight();
	}
	
	private void calculateHeight() {
		if(menuItems != null) {
			height = ((MARGIN * 2) + font.getHeight()) * menuItems.length;
			try{startY = Display.getInstance().getHeight() - Display.MENU_BAR_HEIGHT - height;}catch (Exception e) {}
		}
	}
	
	public void paint(Graphics g, int x, int y, int maxWidth, int maxHeight) {
		y = startY;
		x += leftMargin;
//		g.setColor(UIManager.WHITE_COLOR);
		g.fillRoundRect(x, y, maxWidth - (rightMargin + leftMargin), height, 10, 10);
		
		x += MARGIN;
		
		g.setFont(font);
		g.setColor(0);
		for(int i = 0; i < menuItems.length; i++) {
			//TODO truncate text bigger than one line
			y += MARGIN;
			g.drawString(menuItems[i].getText(), x, y, Graphics.TOP | Graphics.LEFT);
			y += font.getHeight() + MARGIN;
			if(i != menuItems.length -1) {
				g.drawLine(x - MARGIN, y - 1, maxWidth - (leftMargin + rightMargin), y - 1);
			}
		}
	}
	
	public void click(int x, int y) {
		try {
			y -= startY;
			if(y >= 0 && y <= height) {
				int index = y / ((MARGIN * 2) + font.getHeight());
				if(index < menuItems.length && listener != null) {
					listener.menuItemClicked(menuItems[index]);
				}
			}
		}catch (Exception e) {
		}
	}

	public void pressFire() {
		click(0, 0);
	}

}
